<?php
  session_start();
  date_default_timezone_set('Asia/Kolkata');

  $debug = 0;

  $host = 'localhost';
  $username = 'root';
  $password = '';
  $db_name = 'nb158g';

  #db connection
  mysql_connect($host, $username, $password) or exit(mysql_error());

  # db selection
  mysql_select_db($db_name)or exit(mysql_error());

  function pr1($data='')
  {
    global $debug;
    if($debug) {
      echo '<pre style="color:#fff;background:#000;font-size:20px;padding:5px;  font-weight:bold;">';
      print_r($data);
      echo '</pre>';
    }
  }

  function pr($data='')
  {
    global $debug;
    if($debug) {
      echo '<pre style="color:red;background:yellow;font-size:20px;padding:5px;  font-weight:bold;">';
      print_r($data);
      echo '</pre>';
    }
  }

  function vx($data='')
  {
    global $debug;
    if($debug) {
      echo '<pre style="color:red;background:yellow;font-size:20px;padding:5px;  font-weight:bold;">';
      var_export($data);
      echo '</pre>';
    }
  }

  function vd($data='')
  {
    global $debug;
    if($debug) {
      echo '<pre style="color:red;background:yellow;font-size:20px;padding:5px;  font-weight:bold;">';
      var_dump($data);
      echo '</pre>';
    }
  }



  ////////////// DB FUNCTIONS /////////////
  /* used to return status as string
   *
   * @param $status INT
   * @return Status in STRING as active/inactive
   * */
  function getStatus($status=0){

    return ($status==0) ? 'In Active' : 'Active';
  }


  function update($tableName='',$data=array(),$where='')
  {
    if($tableName=='') {
      return false;
    }
    if(!empty($where)){
      $where = "WHERE $where";
    }

    $dataQuery = '';
    foreach($data as $colName=>$colValue){
      $dataQuery .= "$colName='$colValue',";
    }
    $dataQuery = rtrim($dataQuery,',');
    $update_query = "UPDATE `$tableName` SET $dataQuery $where ";
    pr1($update_query);
    mysql_query($update_query) or die(mysql_error());
    $affected_rows = mysql_affected_rows();
    return $affected_rows;
  }

  function fetchAll($tableName='',$where='',$orderBy='',$limit='')
  {
    if($tableName=='') {
      return false;
    }

    if(!empty($where)){
      $where = "WHERE $where";
    }

    if(!empty($orderBy)){
      $orderBy = "ORDER BY $orderBy";
    }

    if(!empty($limit)){
      $limit = "LIMIT $limit";
    }

    $query = "SELECT * FROM `$tableName` $where $orderBy $limit";
    pr1($query);
    $result  = mysql_query($query) or die(mysql_error());
    return $result;
  }

  function countAll($tableName='',$where='')
  {
    if($tableName=='') {
      return false;
    }

    if(!empty($where)){
      $where = "WHERE $where";
    }

    $query = "SELECT COUNT(*) AS `total` FROM `$tableName` $where";
    pr1($query);
    $result  = mysql_query($query) or die(mysql_error());
    $ans = mysql_fetch_assoc($result);
    return $ans['total'];
  }

  function fetchById($tableName='',$id=0)
  {
    if($tableName=='') {
      return false;
    }

    $query = "SELECT * FROM `$tableName` WHERE `id`='$id'";
    pr1($query);
    $result  = mysql_query($query) or die(mysql_error());
    return mysql_fetch_assoc($result);
  }

  function fetchOne($tableName='',$where='')
  {
    if($tableName=='') {
      return false;
    }

    if(!empty($where)){
      $where = "WHERE $where";
    }

    $query = "SELECT * FROM `$tableName` $where";
    pr1($query);
    $result  = mysql_query($query) or die(mysql_error());
    return mysql_fetch_assoc($result);
  }



  /*
   * INSERT KEY=>VALUE pairs in DB Table\
   * @param  $tableName STRING "Name Of DB Table"
   * @param  $data ARRAY "Key=>Value pairs as ColumnName=>Value"
   * @return INT Inserted Id
   *
   * */
  function insert($tableName='',$data=array())
  {

   $query = "INSERT INTO `$tableName` SET";
   $subQuery = '';
   foreach($data as $columnName=>$colValue) {
      $subQuery  .= "`$columnName`='$colValue',";
   }
    $subQuery =  rtrim($subQuery,", ");
    $query .= $subQuery;
    pr1($query);
    mysql_query($query) or die(mysql_error());
    return mysql_insert_id();
  }


  function deleteById($tableName='',$id=0)
  {
    if($tableName=='')return false;
    $query = "DELETE FROM `$tableName` WHERE `id`='$id'";
    pr1($query);
    mysql_query($query) or die(mysql_error());
    return mysql_affected_rows();
  }


  function delete($tableName='',$where='')
  {
    if($tableName=='' || $where=='')return false;

    $query = "DELETE FROM `$tableName` WHERE $where";
    pr1($query);
    mysql_query($query) or die(mysql_error());
    return mysql_affected_rows();
  }


  function fetchCategories()
  {
    $cat = array(1=>'Apple',
                 2=>'Sony',
                 3=>'Samsung',
                 4=>'Toshiba',
                 5=>'LG');

    return $cat;
  }


  function displaySelectCategories($selectName='category_id',$selected='')
  {
    $allCat = fetchCategories();

    $sel='<select name="'.$selectName.'" required >';

    $sel.='<option value="">-Select-</option>';

    foreach( $allCat as $catId=>$catName ) {
      $selected = ($catId==$selected) ? 'selected' :'';

      $sel.="<option $selected value=\"$catId\">$catName</option>";
    }
      $sel.='</select>';

    return $sel;
  }

  function success($msg='') {

    return '<div class="alert alert-success success">'.$msg.'</div>';
  }

  function error($msg='') {

    return '<div class="alert alert-danger error">'.$msg.'</div>';
  }

  function upload($files=array(),$uploadDir='')
  {
    $allowedSize = 1;//1 MB
    $fileSize = 1*1024*1024;//1 MB

    $fieldName = 'image';
    $file_name = $files[$fieldName]['name'];
    $file_name = date('ymdHis').'_'.uniqid().'_'.$file_name;
    $src = $files[$fieldName]['tmp_name'];
    $dest = "{$uploadDir}/{$file_name}";

$allowedTypes = array('images/png','images/jpg','image/jpeg');
$allowedExtn = implode(',',$allowedTypes);

if(in_array($files[$fieldName]['type'],$allowedTypes))
{
    if($files[$fieldName]['size']<=$fileSize) {

      move_uploaded_file($src,$dest);
      return array('flag'=>'on','name'=>$file_name);
    } else {
      return array('flag'=>'off','msg'=>error("File size exceed to $allowedSize "));
    }
} else {
      return array('flag'=>'off','msg'=>error("Please upload file with allowed ($allowedExtn) extn."));
}


  }


  function redirect($page=''){
    if($page){
        header("location:$page");
        exit;
    }
  }




